<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\GoodStore;
use App\GoodStoreMember;
use Validator;
use App\GoodClass;
use App\GoodDefaultClass;
use Illuminate\Support\Facades\DB;
use App\Good;
use App\GoodColor;
use App\GoodColorSize;
use App\GoodUserDefine;
use App\AppToken;
class GoodController extends Controller
{
    //
    public function create(Request $request) {
        $validator = Validator::make($request->all(), array(
            'classId' => 'required|integer',
            'name' => 'required|max:255',
            'no' => 'required|max:255',
            'brand' => 'required|max:255',
            'inputPrice' => 'required|numeric',
            'outputPrice' => 'required|numeric',
            'provider' => 'required|max:255',
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $member = DB::table('good_store_members')
            ->where('memberId', $request->userId)
            ->first();

        $good = new Good();
        $good->classId = $request->classId;
        $good->name = $request->name;
        $good->no = $request->no;
        $good->brand = $request->brand;
        $good->inputPrice = (float)$request->inputPrice;
        $good->outputPrice = (float)$request->outputPrice;
        $good->provider = $request->provider;
        $good->discount = $request->discount;
        $good->storeId = $member->storeId;
        $good->save();
        
        
        $colorDatas = json_decode($request->color);
        if ($colorDatas != null) {
            foreach($colorDatas as $colorData) {
                $color = new GoodColor();
                $color->goodId = $good->id;
                $color->name = $colorData->name;
                $color->picture = $this->addPicture($request->picture);
                $color->save();
                if ($colorData->sizeDatas != null)
                {
                    foreach($colorData->sizeDatas as $sizeData) {
                        $size = new GoodColorSize();
                        $size->colorId = $color->id;
                        $size->size = $sizeData->size;
                        $size->number = $sizeData->number;
                        $size->onStackNumber = $sizeData->onStackNumber;
                        $size->isDiscount = $sizeData->isDiscount;
                        $size->save();
                    }
                }
            }
        }
        $defineDatas = json_decode($request->userDefine);
        if ($defineDatas != null) {
            foreach($defineDatas as $defineData) {
                $define = new GoodUserDefine();
                $define->goodId = $good->id;
                $define->key = $defineData->key;
                $define->value = $defineData->value;
                $define->save();
            }
        }
        $this->returnEcho();
    }
    
    public function findGoods(Request $request) {
        $validator = Validator::make($request->all(), array(
            'classId' => 'required|integer',
            'userId' => 'required|string',
            'perPage' => 'required|integer',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;


        $member = DB::table('good_store_members')
            ->where('memberId', $request->userId)
            ->first();

        if ($request->classId == 0) {
            $class = GoodDefaultClass::where('storeId', $member->storeId);
            $description = $class->description;
        }
        else {
            $class = GoodClass::find($request->classId);
            $description = $class->description;
        }

        $goods = Good::where('classId', $request->classId)->where('storeId', $member->storeId)
            ->paginate($request->perPage);
        $pageData = [
            "count" => $goods->count(),
            "currentPage" => $goods->currentPage(),
            "lastPage" => $goods->lastPage()
        ];
        $list = [];
        foreach($goods as $good) {
            $color = GoodColor::where('goodId', $good->id)->first();
            $picture = '';
            if ($color != null)
                $picture = $color->picture;
            array_push($list, [
                'id' => $good->id,
                'name' => $good->name,
                'price' => $good->outputPrice,
                'picture' => $picture
            ]);
        }
        $data = ["class" => ["description" => $description],"pageData"=>$pageData, "list" => $list];

        $this->returnEcho(200, '', $data);
    }

    public function find(Request $request) {
        $validator = Validator::make($request->all(), array(
            'goodId' => 'required|integer',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $good = Good::find($request->goodId);
        $total = 0;
        $colorData = [];
        $colors = GoodColor::where('goodId', $request->goodId)->get();
        $cnt = 1;
        $picture = '';
        $topflag = 1;
        foreach ($colors as $color) {
            $sizeData = [];
            $flag = 1;
            $sizes = GoodColorSize::where('colorId', $color->id)->get();
            foreach ($sizes as $size) {
                array_push($sizeData, ['sizeId' => strval($size->id), 'size' => $size->size, 'number' => $size->number, 'onStackNumber' => $size->onStackNumber, 'isDiscount' => $size->isDiscount]);
                $total += ($size->number + $size->onStackNumber);
                if ($size->isDiscount == 0) {
                    $flag = 0;
                    $topflag = 0;
                }
            }
            if ($cnt == 1) {
                $picture = $color->picture;
                $cnt--;
            }
            $isDiscount = 0;
            if ($flag == 1)
                $isDiscount = 1;
            array_push($colorData, ['colorId' => strval($color->id), 'name' => $color->name, 'picture' => $color->picture, 'sizeData' => $sizeData, 'isDiscount' => $isDiscount]);
        }
        $defineData = [];
        $defines = GoodUserDefine::where('goodId', $request->goodId)->get();
        foreach ($defines as $define) {
            array_push($defineData, ['defineId' => $define->id, 'key' => $define->key, 'value' => $define->value]);
        }
        $bPic = '';
        if ($good->bPic != null)
            $bPic = $good->bPic;
        $isDiscount = 1;
        if ($topflag == 0)
            $isDiscount  = 0;
        $data = [
            'classId' => $good->classId,
            'name' => $good->name,
            'id' => $good->id,
            'no' => $good->no,
            'brand' => $good->brand,
            'inputPrice' => $good->inputPrice,
            'outputPrice' => $good->outputPrice,
            'provider' => $good->provider,
            'number' => $total,
            'discount' => $good->discount,
            'isDiscount' => $isDiscount,
            'bPic' => $bPic,
            'picture' => $picture,
            'colorData' => $colorData,
            'userDefineData' => $defineData,
        ];

        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => $data]);

    }

    public function delete(Request $request) {
        $validator = Validator::make($request->all(), array(
            'goodIds' => 'required',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $goodIds = json_decode($request->goodIds);
        foreach($goodIds as $goodId ){
            $good = Good::find($goodId);
            $good->delete();
        }

        $this->returnEcho();
    }

    public function edit(Request $request) {
        $validator = Validator::make($request->all(), array(
            'goodId' => 'required|integer',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;
        $dir = 'uploads/'.date('Y-m-d');
        if (!is_dir($dir))
            mkdir($dir);

        $member = GoodStoreMember::where('memberId', $request->userId)->first();

        $goods = Good::where('storeId', $member->storeId)->get();
        foreach ($goods as $good) {
            if ($good->no == $request->no) {
                echo json_encode(['status' => 403, 'errmsg' => "this no couldn't be used", 'data' => 0]);
                return ;
            }
        }

        $good = Good::find($request->goodId);
        if ($request->name)
            $good->name = $request->name;
        if ($request->no)
            $good->no = $request->no;
        if ($request->brand)
            $good->brand = $request->brand;
        if ($request->inputPrice)
            $good->inputPrice = $request->inputPrice;
        if ($request->outputPrice)
            $good->outputPrice = $request->outputPrice;
        if ($request->provider)
            $good->provider = $request->provider;
        if ($request->discount)
            $good->discount = $request->discount;

        $good->save();

        $colorDatas = json_decode($request->color);
        if ($colorDatas != null) {
            foreach($colorDatas as $colorData) {
                if ($colorData->type == 1) {
                    $color = new GoodColor();
                    $color->goodId = $good->id;
                    $color->name = $colorData->name;
                    $imgData = base64_decode($colorData->picture);
                    $filename = $dir . '/' . str_random(6) . '.jpg';
                    file_put_contents($filename, $imgData);
                    $color->picture = $filename;
                    $color->save();
                    if ($colorData->sizeDatas != null) {
                        foreach ($colorData->sizeDatas as $sizeData) {
                            $size = new GoodColorSize();
                            $size->colorId = $color->id;
                            $size->size = $sizeData->size;
                            $size->number = $sizeData->number;
                            $size->save();
                        }
                    }
                }
                else if ($colorData->type == 2) {
                    $color = GoodColor::find($colorData->colorId);
                    if ($colorData->name)
                        $color->name = $colorData->name;
                    if ($colorData->picture) {
                        $imgData = base64_decode($colorData->picture);
                        $filename = $dir . '/' . str_random(6) . '.jpg';
                        file_put_contents($filename, $imgData);
                        $color->picture = $filename;
                    }
                    $color->save();
                }
                else if ($colorData->type == 3) {
                    $color = GoodColor::find($colorData->colorId);
                    $color->delete();
                }
            }
        }
        $sizeDatas = json_decode($request->size);
        if ($sizeDatas != null) {
            foreach ($sizeDatas as $sizeData) {
                if ($sizeData->type == 1) {
                    $size = new GoodColorSize();
                    $size->colorId = $sizeData->colorId;
                    $size->size = $sizeData->size;
                    $size->number = $sizeData->number;
                    $size->save();
                }
                else if ($sizeData->type == 2) {
                    $size = GoodColorSize::find($sizeData->sizeId);
                    if ($sizeData->size)
                        $size->size = $sizeData->size;
                    if ($sizeData->number)
                        $size->number = $sizeData->number;
                    $size->save();
                }
                else if ($sizeData->type == 3) {
                    $size = GoodColorSize::find($sizeData->sizeId);
                    $size->delete();
                }
            }
        }

        $defineDatas = json_decode($request->userDefine);
        if ($defineDatas != null) {
            foreach($defineDatas as $defineData) {
                if ($defineData->type == 1) {
                    $define = new GoodUserDefine();
                    $define->goodId = $good->id;
                    $define->key = $defineData->key;
                    $define->value = $defineData->value;
                    $define->save();
                }
                else if($defineData->type == 2) {
                    $define = GoodUserDefine::find($defineData->id);
                    if ($defineData->key)
                        $define->key = $defineData->key;
                    if ($defineData->value)
                        $define->value = $defineData->value;
                    $define->save();
                }
                else if ($defineData->type == 3) {
                    $define = GoodUserDefine::find($defineData->id);
                    $define->delete();
                }
            }
        }
        echo json_encode(['status'=> 200, 'errmsg' => '', 'data' => []]);
    }

    public function addBPic(Request $request) {
        $validator = Validator::make($request->all(), array(
            'goodId' => 'required|integer',
            'bPic' => 'required',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;


        $dir = 'uploads/'.date('Y-m-d');
        if (!is_dir($dir))
            mkdir($dir);
        $good = Good::find($request->goodId);
        $imgData=base64_decode($request->bPic);
        $filename = $dir.'/'.str_random(6).'.jpg';
        file_put_contents($filename, $imgData);
        $good->bPic = $filename;
        $good->save();

        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => []]);
    }

    public function changeClass(Request $request) {
        $validator = Validator::make($request->all(), array(
            'classId' => 'required|integer',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $goodIds = json_decode($request->goodIds);
        foreach($goodIds as $goodId ){
            $good = Good::find($goodId);
            $good->classId = $request->classId;
            $good->save();
        }

        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => []]);
    }

    public function editDiscount(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'goodId' => 'required'
        ));
        if ($validator->fails()) {
            echo json_encode(['status' => 0, 'errmsg' => $validator->errors(), 'data' => []]);
            return ;
        }
        $token = new \App\AppToken();
        $result = $token->ValidateSession($request->sessionId);
        if ($result == false) {
            echo json_encode(['status' => 403, 'errmsg' => 'sessionId not found', 'data' => []]);
            return ;
        }

        $good = \App\Good::find($request->goodId);
        $good->outputPrice = $request->outputPrice;
        $good->discount = $request->discount;
        $listDatas = json_decode($request->list);
        foreach ($listDatas as $listData) {
            $colorData = $listData;
            $color = \App\GoodColor::where('goodId', $request->goodId)->where('name', $colorData->color)->first();
            $sizeDatas = $colorData->sizeData;
            foreach ($sizeDatas as $sizeData) {
                $size = \App\GoodColorSize::where('colorId', $color->id)->where('size', $sizeData->size)->first();
                $size->isDiscount = $sizeData->isDiscount;
                $size->save();
            }
        }
        $good->save();
        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => []]);
    }

    public function getDiscountMsg(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'goodId' => 'required'
        ));
        if ($validator->fails()) {
            echo json_encode(['status' => 0, 'errmsg' => $validator->errors(), 'data' => []]);
            return ;
        }
        $token = new \App\AppToken();
        $result = $token->ValidateSession($request->sessionId);
        if ($result == false) {
            echo json_encode(['status' => 403, 'errmsg' => 'sessionId not found', 'data' => []]);
            return ;
        }

        $good = \App\Good::find($request->goodId);
        $colorData = [];
        $isGoodDiscount = 1;
        $colors = \App\GoodColor::where('goodId', $good->id)->get();
        foreach ($colors as $color) {
            $sizeData = [];
            $sizes = \App\GoodColorSize::where('colorId', $color->id)->get();
            $isColorDiscount = 1;
            foreach ($sizes as $size) {
                array_push($sizeData, ['size' => $size->size, 'isDiscount' => $size->isDiscount]);
                if ($size->idDiscount == 0) {
                    $isColorDiscount = 0;
                    $isGoodDiscount = 0;
                }
            }
            array_push($colorData, ['color' => $color->name, 'isDiscount' => $isColorDiscount, 'sizeData' => $sizeData]);
        }

        echo json_encode(['status'=>200, 'errmsg' => '', 'data' => [
            'outputPrice' => $good->outputPrice,
            'discount' => $good->discount,
            'isDiscount' => $isGoodDiscount,
            'list' => $colorData,
        ]]);
    }
    public function getDefault(Request $request) {
        $validator = Validator::make($request->all(), array(
            'sessionId' => 'required|max:255',
            'userId' => 'required'
        ));
        if ($validator->fails()) {
            echo json_encode(['status' => 0, 'errmsg' => $validator->errors(), 'data' => []]);
            return ;
        }
        $token = new \App\AppToken();
        $result = $token->ValidateSession($request->sessionId);
        if ($result == false) {
            echo json_encode(['status' => 403, 'errmsg' => 'sessionId not found', 'data' => []]);
            return ;
        }
        $member = GoodStoreMember::where('memberId', $request->userId)->first();

        $good = Good::where('storeId', $member->storeId)->where('classId', 0)->first();

        if ($good == null)
        {
            echo json_encode(['status' => 404, 'errmsg' => 'good not found', 'data' => 0]);
            return ;
        }

        $total = 0;
        $colorData = [];
        $colors = GoodColor::where('goodId', $good->id)->get();
        $cnt = 1;
        $picture = '';
        $topflag = 1;
        foreach ($colors as $color) {
            $sizeData = [];
            $flag = 1;
            $sizes = GoodColorSize::where('colorId', $color->id)->get();
            foreach ($sizes as $size) {
                array_push($sizeData, ['sizeId' => strval($size->id), 'size' => $size->size, 'number' => $size->number, 'onStackNumber' => $size->onStackNumber, 'isDiscount' => $size->isDiscount]);
                $total += ($size->number + $size->onStackNumber);
                if ($size->isDiscount == 0) {
                    $flag = 0;
                    $topflag = 0;
                }
            }
            if ($cnt == 1) {
                $picture = $color->picture;
                $cnt--;
            }
            $isDiscount = 0;
            if ($flag == 1)
                $isDiscount = 1;
            array_push($colorData, ['colorId' => strval($color->id), 'name' => $color->name, 'picture' => $color->picture, 'sizeData' => $sizeData, 'isDiscount' => $isDiscount]);
        }
        $defineData = [];
        $defines = GoodUserDefine::where('goodId', $request->goodId)->get();
        foreach ($defines as $define) {
            array_push($defineData, ['defineId' => $define->id, 'key' => $define->key, 'value' => $define->value]);
        }
        $bPic = '';
        if ($good->bPic != null)
            $bPic = $good->bPic;
        $isDiscount = 1;
        if ($topflag == 0)
            $isDiscount  = 0;
        $data = [
            'classId' => $good->classId,
            'name' => $good->name,
            'id' => $good->id,
            'no' => $good->no,
            'brand' => $good->brand,
            'inputPrice' => $good->inputPrice,
            'outputPrice' => $good->outputPrice,
            'provider' => $good->provider,
            'number' => $total,
            'discount' => $good->discount,
            'isDiscount' => $isDiscount,
            'bPic' => $bPic,
            'picture' => $picture,
            'colorData' => $colorData,
            'userDefineData' => $defineData,
        ];

        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => $data]);
    }

    public function getColorSizeNumber(Request $request) {
        $validator = Validator::make($request->all(), array(
            'sessionId' => 'required|max:255',
            'userId' => 'required',
            'color' => 'required',
            'size' => 'required',
            'goodId' => 'required'
        ));
        if ($validator->fails()) {
            echo json_encode(['status' => 0, 'errmsg' => $validator->errors(), 'data' => []]);
            return ;
        }
        $token = new AppToken();
        $result = $token->ValidateSession($request->sessionId);
        if ($result == false) {
            echo json_encode(['status' => 403, 'errmsg' => 'sessionId not found', 'data' => []]);
            return ;
        }

        $good = Good::find($request->goodId);
        $color = GoodColor::where('goodId', $good->id)->where('name', $request->color)->first();
        $size = GoodColorSize::where('colorId', $color->id)->where('size', $request->size)->first();

        $data = [
            "onStackNumber" => $size->onStackNumber,
            "number" => $size->number
        ];

        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => $data]);
    }

    public function hasNo(Request $request) {
        $validator = Validator::make($request->all(), array(
            'goodId' => 'required|max:255',
            'mode' => 'required|integer',
            'sessionId' => 'required|max:255',
            'no' => 'required',
            'userId' => 'required'
        ));
        if ($validator->fails()) {
            echo json_encode(['status' => 0, 'errmsg' => $validator->errors(), 'data' => []]);
            return ;
        }
        $token = new AppToken();
        $result = $token->ValidateSession($request->sessionId);
        if ($result == false) {
            echo json_encode(['status' => 403, 'errmsg' => 'sessionId not found', 'data' => []]);
            return ;
        }
        $member = GoodStoreMember::where('memberId', $request->userId)->first();

        $goods = Good::where('storeId', $member->storeId)->get();
        foreach ($goods as $good) {
            if ($good->no == $request->no) {
                echo json_encode(['status' => 200, 'errmsg' => '', 'data' => 0]);
                return ;
            }
        }
        if ($request->mode == 0) {
            echo json_encode(['status' => 200, 'errmsg' => '', 'data' => 1]);
        }
        else  {
            $good = Good::find($request->goodId);
            $good->no = $request->no;
            $good->save();
            echo json_encode(['status' => 200, 'errmsg' => '', 'data' => 1]);
        }
    }

    public function getFromClass(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'classId' => 'required'
        ));
        if ($validator->fails()) {
            echo json_encode(['status' => 0, 'errmsg' => $validator->errors(), 'data' => []]);
            return ;
        }
        $token = new AppToken();
        $result = $token->ValidateSession($request->sessionId);
        if ($result == false) {
            echo json_encode(['status' => 403, 'errmsg' => 'sessionId not found', 'data' => []]);
            return ;
        }

        $member = GoodStoreMember::where('memberId', $request->userId)->first();

        $goods = \App\Good::where('classId', $request->classId)->where('storeId', $member->storeId)->get();

        $list = [];

        foreach ($goods as $good) {
            $picture = '';
            $color = \App\GoodColor::where('goodId', $good->id)->first();
            if ($color != null) {
                $picture = $color->picture;
            }
            array_push($list, ['goodId' => $good->id, 'name' => $good->name, 'no' => $good->no, 'picture' => $picture]);
        }

        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => ['list' => $list]]);

    }

}
